
package com.v1.video.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.v1.video.R;
import com.v1.video.adapter.OptionRecommendAdapter;
import com.v1.video.domain.RecommendAppInfo;
import com.v1.video.domain.RecommendAppPageInfo;
import com.v1.video.domain.RecommendInfoApp;
import com.v1.video.option.db.RecommendAppDbUtil;
import com.v1.video.option.util.DownloadAppUtil;
import com.v1.video.option.util.SearchAboutUtil;
import com.v1.video.util.Logger;

public class SettingRecommendAppActivity extends BaseActivity implements OnClickListener {
    private final String TAG = "SettingRecommendAppActivity";

    private ListView listView;

    private List<RecommendAppInfo> listInfo = null;
    List<RecommendAppInfo> listApp = new ArrayList<RecommendAppInfo>();
    // private SettingTopTimeAdapter adapter;
//    private PullToRefreshListView appRefreshListView;
    private TextView txtTitle = null;
    OptionRecommendAdapter adapter = null;
//    private MyDialog dialogCommon;
    public static boolean isCanRefresh = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting_recommend_app);
    }

    @Override
    protected void initView() {
//        appRefreshListView = (PullToRefreshListView) findViewById(R.id.recommend_list);        
//        listView = appRefreshListView.getRefreshableView();
//        appRefreshListView.setScrollingWhileRefreshingEnabled(false);        
//        appRefreshListView.setMode(Mode.DISABLED);
    	txtTitle = (TextView)findViewById(R.id.tv_title);
        listView = (ListView)findViewById(R.id.recommend_list); 
    }

    @Override
    protected void initData() {
        // adapter = new SettingTopTimeAdapter(this);
        // listView.setAdapter(adapter);
        // adapter.addItem(new TopTime(6, 32), false);
    	txtTitle.setText(R.string.about_label_app);
//        listInfo = RecommendAppDbUtil.getAppInfo(SettingRecommendAppActivity.this);//ft_12.4**********
//        if (listInfo != null) {
////            Logger.i(TAG, "listInfo.size=" + listInfo.size());
//            if (listInfo.size() > 0) {
//                for(int i = 0; i < listInfo.size();i++){
//                    RecommendAppInfo app = listInfo.get(i);
////                    Logger.i(TAG, "app.progress=="+ i + app.progress);
//                    if(app.state == 0){
//                        app.state = 1;
//                        RecommendAppDbUtil.addAppInfo(SettingRecommendAppActivity.this, app);
//                    }
//                    app.status = getAppInState(app);
//                }
//                adapter = new OptionRecommendAdapter(SettingRecommendAppActivity.this, listInfo,
//                        handler);
//                listView.setAdapter(adapter);
//            }else {
//                new GetRecommendAppTask().execute();
//            }
//        } else {//ft_12.4**********
            new GetRecommendAppTask().execute();
//        }
    }

    @Override
    protected void setListener() {
//        findViewById(R.id.iv_result).setOnClickListener(this);
        findViewById(R.id.lay_result).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();
            }
        });
//        appRefreshListView.setOnRefreshListener(new OnRefreshListener2() {
//
//            @Override
//            public void onPullDownToRefresh(PullToRefreshBase refreshView) {
//                // TODO Auto-generated method stub
//                Logger.i(TAG, "下拉");
//            }
//
//            @Override
//            public void onPullUpToRefresh(PullToRefreshBase refreshView) {
//                // TODO Auto-generated method stub
//                Logger.i(TAG, "上拉");
//            }
//        });
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
                // TODO Auto-generated method stub
                Logger.i("OptionRecommendAdapter", "点击应用第几个111=" + pos);
//                appDetailView(pos);
            }           
        });        
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_result:
                finish();
                break;
        // case R.id.imageView_add:
        // new DialogTimeSettting(this).show(new OnConfirmAction() {
        //
        // @Override
        // public void onConfirm(int hour, int minute) {
        // // TODO Auto-generated method stub
        // adapter.addItem(new TopTime(hour, minute), false);
        // }
        // });
        // break;
        }

    }
    
    
    
//    /** 应用介绍 */
//    private void appDetailView(final int pos) {
//        dialogCommon = new MyDialog(this, R.style.dialog_custom);
//        final RecommendAppInfo info = listInfo.get(pos);
////        dialogCommon = new MyDialog(this, R.style.dialog_person_head);
//        dialogCommon.setContentView(R.layout.dialog_app_recommend);
//        dialogCommon.setCancelable(false);
//        dialogCommon.setCanceledOnTouchOutside(false);
//        
//        ImageView icon = (ImageView)dialogCommon.findViewById(R.id.app_icon);
//        TextView txtSure = (TextView)dialogCommon.findViewById(R.id.app_btn_sure);
//        if(info.getImgUrl() != null){
//            if(info.getImgUrl().equals("")){
//                icon.setImageResource(R.drawable.ic_launcher);
//            }else{
//                ImageLoader.getInstance().displayImage(/* Constant.SERVER_IP+ */info.getImgUrl(),
//                        icon, options, new SimpleImageLoadingListener() {
//                            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//                                ImageView iv = (ImageView) view;
//                                iv.setImageBitmap(loadedImage);
//                            }
//                        });
//            }
//        }else{
//            icon.setImageResource(R.drawable.ic_launcher);
//        }
//        
//        ((TextView)dialogCommon.findViewById(R.id.app_name)).setText(info.getAppName());
//        ((TextView)dialogCommon.findViewById(R.id.app_title)).setText(info.getAppTitle());
//        ((TextView)dialogCommon.findViewById(R.id.app_detail)).setText(info.getAppDetail());
//        dialogCommon.findViewById(R.id.app_btn_cancel).setOnClickListener(new OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                dialogCommon.dismiss();
//            }
//        });
//        boolean isDowing = false;
//        if(DownloadAppUtil.downloadList.containsKey(info.getPackageName())){
//            if(DownloadAppUtil.downloadList.get(info.getPackageName()).runnable != null){
//                if(DownloadAppUtil.downloadList.get(info.getPackageName()).runnable.isStop){
//                    
//                }else{
//                    isDowing = true;
//                    txtSure.setText("下载中...");
//                    txtSure.setTextColor(getResources().getColor(R.color.zero_btn_color));
//                }
//            }
//        }else{
//            
//        }
//        final boolean isCanOnclick = isDowing;
//        txtSure.setOnClickListener(new OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                if(isCanOnclick){
//                    //正在下载中，就不去凑热闹了
//                    return;
//                }
//                dialogCommon.dismiss();
//                DownloadAppUtil.outerHandler = adapter.handler;
//                DownloadAppUtil.startDownThread(SettingRecommendAppActivity.this, info, handler,pos);
////                adapter.notifyDataSetChanged();
//            }
//        });
//        dialogCommon.show();
//    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if(keyCode == KeyEvent.KEYCODE_HOME){
            if(listInfo != null){
                for(int i = 0; i < listInfo.size();i++){
                    RecommendAppInfo app = listInfo.get(i);
                    if(!isInstall(app.getPackageName())){
                        DownloadAppUtil.stopDownLoad(app);
                    }
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }



    private class GetRecommendAppTask extends AsyncTask<Void, Void, Void> {

        RecommendAppPageInfo pageInfo = null;

        public GetRecommendAppTask() {
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                SearchAboutUtil util = new SearchAboutUtil();
                pageInfo = util.getRecommendApp();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            if (pageInfo == null) {
                Logger.i(TAG, "返回应用列表数据为空v");
            } else {
                List<RecommendInfoApp> listInfo = null;
                listInfo = pageInfo.getApp_list();
                
                for (int i = 0; i < listInfo.size(); i++) {
                    RecommendInfoApp info = listInfo.get(i);
//                    info.setAppPackageName("cn.v1.www.kongqingdong.android.activity");
//                    info.setDownUrl("http://mingren.v1.cn/dl/kongqingdong.apk");
                    info.saveFilePath = DownloadAppUtil.DOWNLOADDIR + "/" +info.getPackageName()+".apk";
                    info.status = getAppInState(info);
                    
//                    Logger.i(TAG, "appinfo.status=="+info.status);
                    RecommendAppInfo app = new RecommendAppInfo(info);
                    listApp.add(app);
//                    RecommendAppDbUtil.addAppInfo(SettingRecommendAppActivity.this, app);//ft_12.4**********
                }
//                List<RecommendAppInfo> listApp = RecommendAppDbUtil.getAppInfo(SettingRecommendAppActivity.this);//ft_12.4**********
//                adapter = new OptionRecommendAdapter(SettingRecommendAppActivity.this, listApp,
//                        handler);
                adapter = new OptionRecommendAdapter(SettingRecommendAppActivity.this, listApp,
                        handler);
                listView.setAdapter(adapter);
            }
            // mPullRefreshVideo.onRefreshComplete();
        }
    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            Logger.i(TAG, "此处在执行");
            switch(msg.what){
                case RecommendAppInfo.STATUS_GO_DOWN:
                    listInfo.get(msg.arg1).setStatus(msg.what);
                    break;
                case RecommendAppInfo.STATUS_DOWNNING:
                    listInfo.get(msg.arg1).setStatus(msg.what);
                    listInfo.get(msg.arg1).progress = msg.arg2;
                    break;
                case RecommendAppInfo.STATUS_STOP:
                    listInfo.get(msg.arg1).setStatus(msg.what);
                    break;
                case RecommendAppInfo.STATUS_DOWNED:
                    listInfo.get(msg.arg1).setStatus(msg.what);
                    break;
            }
            if (adapter != null) {
                adapter.updata(listInfo);                
            }
        }
    };
    
    class InstallReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
//            List<RecommendAppInfo> listApp = RecommendAppDbUtil.getAppInfo(SettingRecommendAppActivity.this);
            for (int i = 0; i < listApp.size(); i++) {
                RecommendAppInfo info = listApp.get(i);
                info.status = getAppInState(info);
                Logger.i(TAG, "appinfo.status=="+info.status);                
            }
            adapter.updata(listApp);
        }
    }
    
    private void updataListApp(){
    	if(adapter != null){
//	    	List<RecommendAppInfo> listApp = RecommendAppDbUtil.getAppInfo(SettingRecommendAppActivity.this);
	        for (int i = 0; i < listApp.size(); i++) {
	            RecommendAppInfo info = listApp.get(i);
	            info.status = getAppInState(info);
	            Logger.i(TAG, "appinfo.status=="+info.status);                
	        }
	        adapter.updata(listApp);
//	        isCanRefresh = false;
        }
    }
    
    private int getAppInState(RecommendInfoApp app){
        int type = 0;
        if(isInstall(app.getPackageName())){
            type = RecommendAppInfo.STATUS_GO_START;//打开
        }else{
            try{
                if(DownloadAppUtil.isExist(app) == 2){
                    type = RecommendAppInfo.STATUS_DOWNED;//安装
                }else if(DownloadAppUtil.isExist(app) == 1){
                    type = RecommendAppInfo.STATUS_STOP;//继续//暂停
                }else{
                    type = RecommendAppInfo.STATUS_GO_DOWN;//下载
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        
        return type;
    }
    
    private int getAppInState(RecommendAppInfo app){
        int type = 0;
        if(isInstall(app.getPackageName())){
            type = RecommendAppInfo.STATUS_GO_START;//打开
        }else{
            try{
                if(DownloadAppUtil.isExist(app) == 2){
                    type = RecommendAppInfo.STATUS_DOWNED;//安装
                }else if(DownloadAppUtil.isExist(app) == 1){
                    type = RecommendAppInfo.STATUS_STOP;//继续//暂停
                }else{
                    type = RecommendAppInfo.STATUS_GO_DOWN;//下载
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        
        return type;
    }
    
    
    InstallReceiver receiver = new InstallReceiver();
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction("Intent.ACTION_PACKAGE_ADDED");
        filter.addAction("Intent.ACTION_PACKAGE_INSTALL");
        filter.addAction("android.intent.action.PACKAGE_ADDED");
        filter.addAction("android.intent.action.PACKAGE_CHANGED");
        filter.addAction("android.intent.action.PACKAGE_INSTALL");
        filter.addDataScheme("package");
        registerReceiver(receiver, filter);
        MobclickAgent.onPageStart("应用推荐");
        if(isCanRefresh){
        	updataListApp();
        }
    }
    //成功的安装APK之后  //广播：设备上新安装了一个应用程序包。 
    //一个新应用包已经安装在设备上，数据包括包名（最新安装的包程序不能接收到这个广播）     
     
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unregisterReceiver(receiver);
        MobclickAgent.onPageEnd("应用推荐");
    }
    
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
    }

    @Override
    public void finish() {
        // TODO Auto-generated method stub
//        unregisterReceiver(receiver);
        super.finish();
    }
    
    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        if(listInfo != null){
            for(int i = 0; i < listInfo.size();i++){
                RecommendAppInfo app = listInfo.get(i);
                if(!isInstall(app.getPackageName())){
                    DownloadAppUtil.stopDownLoad(app);
                }
            }
        }
        super.onBackPressed();        
    }

    private boolean isInstall(String packageName) {
        if (packageName == null) {
            return false;
        }
        if (packageName.equals("")) {
            return false;
        }
        try {
            ApplicationInfo info = SettingRecommendAppActivity.this.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (NameNotFoundException e) {
            return false;
        }        
    }
    
}
